package com.example.pluggabledemo;

import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;

import java.lang.reflect.Method;

/**
 * @author zy
 * @version 1.0
 * @date 2020/10/19 16:33
 * @description
 * @modified
 */
public class PDApp extends Application {
    public static Context sContext;

    private AssetManager assetManager;
    private Resources resources;
    private Resources.Theme theme;

    public static Context getContext() {
        return sContext;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        sContext = base;
        initPluginResource();
    }

    /**
     * 初始化插件的资源文件，使其访问自己的资源文件
     */
    private void initPluginResource() {
        try {
            assetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = assetManager.getClass().getDeclaredMethod("addAssetPath", String.class);
            addAssetPathMethod.setAccessible(true);
            addAssetPathMethod.invoke(assetManager, Constants.APK_PATH);

            Method ensureStringBlocks = assetManager.getClass().getDeclaredMethod("ensureStringBlocks");
            ensureStringBlocks.setAccessible(true);
            ensureStringBlocks.invoke(assetManager);

            Resources superResource = getResources();
            resources = new Resources(assetManager, superResource.getDisplayMetrics(), superResource.getConfiguration());
            theme = resources.newTheme();
            theme.setTo(super.getTheme());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public AssetManager getAssets() {
        if (assetManager != null) {
            return assetManager;
        }
        return super.getAssets();
    }

    @Override
    public Resources getResources() {
        if (resources != null) {
            return resources;
        }
        return super.getResources();
    }

    @Override
    public Resources.Theme getTheme() {
        if (theme != null) {
            return theme;
        }
        return super.getTheme();
    }
}
